import { Injectable, BadRequestException, SetMetadata } from '@nestjs/common';
import { BaseDao } from '@/common/baseDao/base.service';
import { Util } from '@/common/util/util.service';
import { ApparatusDto } from './apparatus.dto';
import { InsertOneResult, ObjectId } from 'mongodb';
import * as bcrypt from 'bcryptjs';
import Config from '@/config';
import { JwtService } from '@/common/jwt/jwt.service';

@Injectable()
export class ApparatusService {
  constructor(
    private baseDao: BaseDao,
    private util: Util,
  ) {}
  async apparatusUpdate(apparatusDto: ApparatusDto): Promise<any> {
    const { sort, title, _id } = apparatusDto;

    if (!_id) {
      throw new BadRequestException('id不能为空');
    }

    try {
      await this.baseDao.updateById({
        dbName: 'quick-apparatus',
        id: _id,
        dataJson: {
          title,
          sort,
        },
      });

      return {
        success: true,
      };
    } catch (error) {
      throw new BadRequestException(error);
    }
  }

  async apparatusAdd(apparatusDto: ApparatusDto): Promise<any> {
    const { sort, title } = apparatusDto;

    try {
      await this.baseDao.add({
        dbName: 'quick-apparatus',
        dataJson: {
          title,
          sort,
        },
      });

      return {
        success: true,
      };
    } catch (error) {
      throw new BadRequestException(error);
    }
  }

  async getApparatusList({ pageIndex, pageSize, title }): Promise<any> {
    const { _ } = this.util;

    let whereJson = {};
    if (title) {
      whereJson = {
        title: _.eq(title),
      };
    }
    return await this.baseDao.selectRows({
      dbName: 'quick-apparatus',
      whereJson,
      sortArr: [{ name: 'sort', type: 'asc' }],
      pageIndex: Number(pageIndex),
      pageSize: Number(pageSize),
    });
  }

  async apparatusDelete(ids: string[]): Promise<any> {
    const { _ } = this.util;

    if (!ids || ids.length === 0) {
      throw new BadRequestException('ids不能为空');
    }

    try {
      ids.forEach((id) => {
        if (!ObjectId.isValid(id)) {
          throw new BadRequestException(`无效的ID格式: ${id}`);
        }
      });

      const whereJson = {
        _id: _.in(ids),
      };

      const result = await this.baseDao.del({
        dbName: 'quick-apparatus',
        whereJson,
      });
      return result;
    } catch (error) {
      console.log(error);

      throw new BadRequestException(error);
    }
  }
}
